var fs = require('fs');
var express = require('express');
var router = express.Router();
const multer = require('multer');

var createFolder = function (folder) {
  try {
    fs.accessSync(folder);
  } catch (e) {
    fs.mkdirSync(folder);
  }
};

var uploadFolder = './uploads/';

createFolder(uploadFolder);

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadFolder);    // 保存的路径，备注：需要自己创建
  },
  filename: function (req, file, cb) {
    const filelast = file.originalname.split('.')
    cb(null, Date.now() + '.' + filelast[filelast.length-1]);
  }
});

var upload = multer({ storage: storage })

/* POST 文件上传. */
router.post('/', upload.single('file'), function (req, res, next) {
  const result = {};
  if (req.file.path) {
    result.code = 0;
    result.message = '操作成功';
    result.data = '/uploads/' + req.file.filename;
  } else {
    result.code = 1;
    result.message = '上传失败';
    result.data = null;
  }
  res.json(result);
});

module.exports = router;
